﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Filter
{
    /// <summary>
    /// 自定义异常过滤器
    /// </summary>
    public class MyExceptionFilter : System.Attribute,IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                ExceptionResult res = new ExceptionResult();
                res.code = 1;
                res.msg = context.Exception.Message;
                context.Result = new ContentResult
                {
                    // 返回状态码设置为200，表示成功
                    StatusCode = StatusCodes.Status200OK,
                    // 设置返回格式
                    ContentType = "application/json;charset=utf-8",
                    Content = res.ToJson()
                };
                using(mtContext _context = new mtContext())
                {
                    LogHelper.ErrorLog(_context, "ex", context.Exception.ToJson(), context.ActionDescriptor.RouteValues.ToJson(), "MyExceptionFilter", "CB") ;
                }
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
